package com.lwz.startdemo.recyclerview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.lwz.startdemo.R

class FruitAdapter (val fruitList:List<Fruit>):RecyclerView.Adapter<FruitAdapter.ViewHolder>(){

    inner class ViewHolder(view:View):RecyclerView.ViewHolder(view){
        val fruitImage = view.findViewById<ImageView>(R.id.fruit_image)
        val fruitName = view.findViewById<TextView>(R.id.fruit_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false)

        val holder = ViewHolder(view)
        holder.fruitImage.setOnClickListener {
            val position = holder.adapterPosition
            val fruit = fruitList[position]
            Toast.makeText(parent.context,"you clicked item view ${fruit.name}",Toast.LENGTH_SHORT).show()
        }
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            val fruit = fruitList[position]
            Toast.makeText(parent.context,"you clicked item ${fruit.name}",Toast.LENGTH_SHORT).show()
        }


        return holder
    }

    override fun getItemCount(): Int = fruitList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = fruitList[position]
        holder.fruitImage.setImageResource(fruit.res)
        holder.fruitName.text = fruit.name
    }

}